package com.example.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.AirQualitySensor;
import com.example.entity.LightSensor;
import com.example.entity.Params;
import com.example.entity.TemperatureHumiditySensor;
import com.example.repository.AirQualitySensorMapper;
import com.example.repository.TemperatureHumiditySensorMapper;
import com.example.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Service
public class TemperatureHumiditySensorService extends ServiceImpl<TemperatureHumiditySensorMapper, TemperatureHumiditySensor> {

    @Resource
    private TemperatureHumiditySensorMapper temperatureHumiditySensorMapper;


    public PageInfo<TemperatureHumiditySensor> getSensorData(Params params){
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<TemperatureHumiditySensor> search = temperatureHumiditySensorMapper.getSensorData();
        return PageInfo.of(search);
    }

    public double getTemperature(){

        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MINUTE, -20);
        Date twentySecondsAgo = calendar.getTime();
        return temperatureHumiditySensorMapper.selectList(Wrappers.<TemperatureHumiditySensor>lambdaQuery().between(
                        TemperatureHumiditySensor::getCreateTime, DateUtil.date2Str(twentySecondsAgo), DateUtil.date2Str(now)))
                .stream().mapToInt(TemperatureHumiditySensor::getTemperature).average().orElse(0);
    }

    public TemperatureHumiditySensor initPie(){
        return temperatureHumiditySensorMapper.initPie();
    }

    public Map<String, Object> initLineForAdmin(Params params) {

        List<Map<String, Object>> rawList = temperatureHumiditySensorMapper.initLineForAdmin(params);
        // 调用封装的方法
        List<String> dateLabels = generateLastNDaysLabels(params.getPast());
        List<Double> tempList = new ArrayList<>(Collections.nCopies(dateLabels.size(), 0.0));
        List<Double> humList = new ArrayList<>(Collections.nCopies(dateLabels.size(), 0.0));
        Map<String, Integer> dateIndexMap = new HashMap<>();
        for (int i = 0; i < dateLabels.size(); i++) {
            dateIndexMap.put(dateLabels.get(i), i);
        }
        for (Map<String, Object> row : rawList) {
            String date = String.valueOf(row.get("date"));
            Double temp = ((Number) row.get("avg_temperature")).doubleValue();
            Double hum = ((Number) row.get("avg_humidity")).doubleValue();
            Integer idx = dateIndexMap.get(date);
            if (idx != null) {
                tempList.set(idx, temp);
                humList.set(idx, hum);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", dateLabels);
        result.put("temperature", tempList);
        result.put("humidity", humList);
        return result;
    }

    private List<String> generateLastNDaysLabels(int n) {

        List<String> dateLabels = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = n - 1; i >= 0; i--) {
            cal.setTime(new Date());
            cal.add(Calendar.DAY_OF_MONTH, -i);
            dateLabels.add(sdf.format(cal.getTime()));
        }
        return dateLabels;
    }

    public void addTHS(TemperatureHumiditySensor temperatureHumiditySensor){
        temperatureHumiditySensorMapper.insert(temperatureHumiditySensor);
    }

    public void deleteTHS(Long id) {
        temperatureHumiditySensorMapper.deleteById(id);
    }
}
